<?php


namespace app\admin\controller\ord;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\App;
use think\facade\Db;
use think\facade\Validate;

/**
 * @ControllerAnnotation(title="订单列表")
 */
class Order extends AdminController
{

    use \app\admin\traits\Curd;
    protected $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\Order();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
           
            list($page, $limit, $where) = $this->buildTableParames();

            $where = [];
            if(!empty($param['status']) && isset($param['status']))
            {
                $where[] = [
                    ['status', '=', $param['status']],
                ];
            }
            if(!empty($param['order_no']) && isset($param['order_no']))
            {
                $where[] = [
                    ['order_no', '=', $param['order_no']],
                ];
            }
            if(!empty($param['consignee']) && isset($param['consignee']))
            {
                $where[] = [
                    ['consignee', '=', $param['consignee']],
                ];
            }
            if(!empty($param['contact_phone']) && isset($param['contact_phone']))
            {
                $where[] = [
                    ['contact_phone', '=', $param['contact_phone']],
                ];
            }
            if(!empty($param['is_cooperate']) && isset($param['is_cooperate']))
            {
                $where[] = [
                    ['is_cooperate', '=', $param['is_cooperate']],
                ];
            }
            //admin_type  用户类型  type类型（0超管，1业务员，2仓库员）
            $session = session("admin");
           
            //$v["admin_type"] = $session["type"];
            if($session["type"] == 1){
                $count = $this->model
                    ->where($where)
                    ->where("kahuna_id",$session["id"])
                    ->where("delete_time",Null)
                    ->whereNotIn("status","7")
                    ->count();
                $list = $this->model
                    ->where($where)
                    ->where("kahuna_id",$session["id"])
                    ->where("delete_time",Null)
                    ->whereNotIn("status","7")
                    ->page($page, $limit)
                    ->order($this->sort)
                    ->select();
                foreach ($list as $k => $v){
                    //admin_type  用户类型
                    $session = session("admin");
                    $v["admin_type"] = $session["type"];
                    $admin = Db::name("system_admin")->where("id",$v["kahuna_id"])->find();
                    $v["employee_name"] = $admin["employee_name"];
                    $list[$k] = $v;
                }
            }elseif($session["type"] == 2){
                $count = $this->model
                    ->where($where)
                    ->whereNotIn("status","1,7")
                    ->where("delete_time",Null)
                    ->count();
                $list = $this->model
                    ->where($where)
                    ->whereNotIn("status","1,7")
                    ->where("delete_time",Null)
                    ->page($page, $limit)
                    ->order($this->sort)
                    ->select();
                foreach ($list as $k => $v){
                    //admin_type  用户类型
                    $session = session("admin");
                    $v["admin_type"] = $session["type"];
                    $admin = Db::name("system_admin")->where("id",$v["kahuna_id"])->find();
                    $v["employee_name"] = $admin["employee_name"];
                    $list[$k] = $v;
                }
            }else{
                $count = $this->model
                    ->where($where)
                    ->where("delete_time",Null)
                    ->whereNotIn("status","7")
                    ->count();
                $list = $this->model
                    ->where($where)
                    ->where("delete_time",Null)
                    ->whereNotIn("status","7")
                    ->page($page, $limit)
                    ->order($this->sort)
                    ->select();
                foreach ($list as $k => $v){
                    //admin_type  用户类型
                    $session = session("admin");
                    $v["admin_type"] = $session["type"];
                    // $collection_voucher = explode(",",$v["collection_voucher"]);
                    // $v["img"] = $collection_voucher[0];
                    $admin = Db::name("system_admin")->where("id",$v["kahuna_id"])->find();
                    if(!empty($admin["employee_name"])){
                        $v["employee_name"] = $admin["employee_name"];
                    }else{
                        $v["employee_name"] = "";
                    }
                    
                    $list[$k] = $v;
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }else{
            $session = session("admin");
            if($session["type"] == 2 || $session["type"] == 0){
                //有售后
                $count = $this->model
                    ->where("status","8")
                    ->where("delete_time",Null)
                    ->count();
                $this->assign("admin_count",$count);
                //未下单
                $status_1 = $this->model
                ->where("status","1")
                ->where("delete_time",Null)
                ->count();
                $this->assign("status_1",$status_1);

                //待审核
                $status_2 = $this->model
                ->where("status","2")
                ->where("delete_time",Null)
                ->count();
                $this->assign("status_2",$status_2);

                //通过
                $status_3 = $this->model
                ->where("status","3")
                ->where("delete_time",Null)
                ->count();
                $this->assign("status_3",$status_3);

                //驳回
                $status_4 = $this->model
                ->where("status","4")
                ->where("delete_time",Null)
                ->count();
                $this->assign("status_4",$status_4);

                //预约成功
                $status_5 = $this->model
                ->where("status","5")
                ->where("delete_time",Null)
                ->count();
                $this->assign("status_5",$status_5);

                //出库完成
                $status_6 = $this->model
                ->where("status","6")
                ->where("delete_time",Null)
                ->count();
                $this->assign("status_6",$status_6);

                //已打印
                $status_10 = $this->model
                ->where("status","10")
                ->where("delete_time",Null)
                ->count();
                $this->assign("status_10",$status_10);

                //售后完成
                $status_9 = $this->model
                ->where("status","9")
                ->where("delete_time",Null)
                ->count();
                $this->assign("status_9",$status_9);
                
            }
             if($session["type"] == 1){
                //有售后
                $count = $this->model
                    ->where("status","8")
                    ->where("kahuna_id",$session["id"])
                    ->where("delete_time",Null)
                    ->count();
                $this->assign("admin_count",$count);
                //未下单
                $status_1 = $this->model
                ->where("status","1")
                ->where("delete_time",Null)
                ->where("kahuna_id",$session["id"])
                ->count();
                $this->assign("status_1",$status_1);

                //待审核
                $status_2 = $this->model
                ->where("status","2")
                ->where("delete_time",Null)
                ->where("kahuna_id",$session["id"])
                ->count();
                $this->assign("status_2",$status_2);

                //通过
                $status_3 = $this->model
                ->where("status","3")
                ->where("delete_time",Null)
                ->where("kahuna_id",$session["id"])
                ->count();
                $this->assign("status_3",$status_3);

                //驳回
                $status_4 = $this->model
                ->where("status","4")
                ->where("delete_time",Null)
                ->where("kahuna_id",$session["id"])
                ->count();
                $this->assign("status_4",$status_4);

                //预约成功
                $status_5 = $this->model
                ->where("status","5")
                ->where("delete_time",Null)
                ->where("kahuna_id",$session["id"])
                ->count();
                $this->assign("status_5",$status_5);

                //出库完成
                $status_6 = $this->model
                ->where("status","6")
                ->where("delete_time",Null)
                ->where("kahuna_id",$session["id"])
                ->count();
                $this->assign("status_6",$status_6);

                //已打印
                $status_10 = $this->model
                ->where("status","10")
                ->where("delete_time",Null)
                ->where("kahuna_id",$session["id"])
                ->count();
                $this->assign("status_10",$status_10);

                //售后完成
                $status_9 = $this->model
                ->where("status","9")
                ->where("delete_time",Null)
                ->where("kahuna_id",$session["id"])
                ->count();
                $this->assign("status_9",$status_9);
                
            }
            $this->assign("admin_type",$session["type"]);
            return $this->fetch();
        }
      
    }

    public function status_data(){
        $session = session("admin");
        if(empty($session)){
            $this->error("请先登录");
        }
        if($session["type"] == 2 || $session["type"] == 0){
            //有售后
            $count = $this->model->where("status","8")->where("delete_time",Null)->count();
            //未下单
            $status_1 = $this->model->where("status","1")->where("delete_time",Null)->count();
            //待审核
            $status_2 = $this->model->where("status","2")->where("delete_time",Null)->count();
            //通过
            $status_3 = $this->model->where("status","3")->where("delete_time",Null)->count();
            //驳回
            $status_4 = $this->model->where("status","4")->where("delete_time",Null)->count();
            //预约成功
            $status_5 = $this->model->where("status","5")->where("delete_time",Null)->count();
            //出库完成
            $status_6 = $this->model->where("status","6")->where("delete_time",Null)->count();
            //已打印
            $status_10 = $this->model->where("status","10")->where("delete_time",Null)->count();
            //售后完成
            $status_9 = $this->model->where("status","9")->where("delete_time",Null)->count();
        }elseif($session["type"] == 1){
            //有售后
            $count = $this->model->where("status","8")->where("kahuna_id",$session["id"])->where("delete_time",Null)->count();
            //未下单
            $status_1 = $this->model->where("status","1")->where("delete_time",Null)->where("kahuna_id",$session["id"])->count();
            //待审核
            $status_2 = $this->model->where("status","2")->where("delete_time",Null)->where("kahuna_id",$session["id"])->count();
            //通过
            $status_3 = $this->model->where("status","3")->where("delete_time",Null)->where("kahuna_id",$session["id"])->count();
            //驳回
            $status_4 = $this->model->where("status","4")->where("delete_time",Null)->where("kahuna_id",$session["id"])->count();
            //预约成功
            $status_5 = $this->model->where("status","5")->where("delete_time",Null)->where("kahuna_id",$session["id"])->count();
            //出库完成
            $status_6 = $this->model->where("status","6")->where("delete_time",Null)->where("kahuna_id",$session["id"])->count();
            //已打印
            $status_10 = $this->model->where("status","10")->where("delete_time",Null)->where("kahuna_id",$session["id"])->count();
            //售后完成
            $status_9 = $this->model->where("status","9")->where("delete_time",Null)->where("kahuna_id",$session["id"])->count();
        }

        return json([
            "code"=>1,
            "msg"=>"获取成功",
            "data"=>[
                "admin_count"=>$count,
                "status_1"=>$status_1,
                "status_2"=>$status_2,
                "status_3"=>$status_3,
                "status_4"=>$status_4,
                "status_5"=>$status_5,
                "status_6"=>$status_6,
                "status_10"=>$status_10,
                "status_9"=>$status_9,
            ]
        ]);
        
    }

    //批量审核通过
    public function batch_pass(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if (empty($post["id"])) {
                $this->error('订单id不能为空');
            }
            $oid = explode(",",$post["id"]);
            foreach($oid as $k=>$v){
                $ret = $this->model->where('id', $v)->where('status',2)->find();
                if (empty($ret)) {
                    $this->error('当前订单状态不能通过');
                }
                $this->model->where('id', $v)->update([
                    "status"=>3,
                ]);
             
            }
            $this->success('操作成功');
        }
    }


    /**
    * @NodeAnotation(title="添加")
    */
    public function add()
    {
        if ($this->request->isAjax()) {
            $session = session("admin");
            $post = $this->request->param();
            //status 1保存   2确定下单->待审核
            if(empty($post['status'])){
                $this->error('状态不能为空');
            }
            if(empty($post['goodsArr'])){
                $this->error('商品不能为空');
            }
            if(empty($post['contact_phone'])){
                $this->error('联系电话不能为空');
            }
            if(empty($post['provinces'])){
                $this->error('省不能为空');
            }
       
            //dump(!preg_match("/^1[34578]\d{9}$/", $post['contact_phone']));die;
            // if (!preg_match("/^1[34578]\d{9}$/", $post['contact_phone'])) {
            //     $this->error('联系电话格式不正确');
            // } 
 
            if(empty($post['consignee'])){
                $this->error('收货人不能为空');
            }
            if(empty($post['address'])){
                $this->error('收货地址不能为空');
            }
            if(empty($post['amount_collected'])){
                $this->error('收款金额不能为空');
            }
            if(empty($post['collection_voucher'])){
                $this->error('收款凭证不能为空');
            }
            $order_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$session['id'];
            $goodsArr = $post['goodsArr'];
            
            foreach($goodsArr as $k=>$v){
                $goods = Db::name("goods")->where("id",$v["gid"])->find();
                $v["good_bottom_price"] = $goods["bottom_price"];
                $goodsArr[$k] = $v;
            }
            $lisy = [];
            foreach($goodsArr as $ke=>$va){
                $flsst = bcmul($va["good_bottom_price"],$va["num"]);
                array_push($lisy,$flsst);
            }
            $order_bottom_price = array_sum($lisy);
            $expiration_deletion_time = date("Y-m-d H:i:s",strtotime("45 day"));
            $expiration_deletion_time = strtotime($expiration_deletion_time);

            $data = [
                "order_bottom_price"=>$order_bottom_price,
                'order_no'=>$order_no,
                'kahuna_id'=>$session['id'],//负责人==下单人
                'kahuna_name'=>$session['username'],
                'remark'=>$post['remark'],//备注
                'consignee'=>$post['consignee'],//收货人
                'contact_phone'=>$post['contact_phone'],//联系电话
                'amount_collected'=>$post['amount_collected'],//收款金额
                'collection_voucher'=>$post['collection_voucher'],//收款凭证
                'is_cooperate'=>$post['is_cooperate'],//是否合作快递
                'cooperative_express'=>$post['cooperative_express'],//指定快递名称
                'provinces'=>$post['provinces'],//省
                'city'=>$post['city'],//市
                'area'=>$post['area'],//区
                'address'=>$post['address'],//详细地址
                "status"=>$post['status'],
                'create_time'=>time(),
                'expiration_deletion_time'=>$expiration_deletion_time
            ];
            try {
               $save = Db::name("order")->insert($data);
               $orderId = Db::name('order')->getLastInsID();
               if($post['status'] == 2){
                    //添加未读消息提示
                    Db::name("message_prompt")->insert([
                        "oid"=>$orderId,
                        "type"=>1
                    ]);
               }
               $this->txm($orderId);
               //添加商品信息 
               foreach($goodsArr as $k=>$v){
                    $v["oid"] = $orderId;
                    $goodsArr[$k] = $v;
                    // $good_data = [
                    //     "good_name"=>$v["good_name"],
                    //     "gid"=>$v["gid"],
                    //     "num"=>$v["num"],
                    //     "good_bottom_price"=>$v["good_bottom_price"],
                    //     "oid"=>$orderId
                    // ];
               }
            //   dump($goodsArr);die;
               Db::name('order_item')->insertAll($goodsArr); 
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }else{
            $good_type = Db::name("good_type")->order("id desc")->select()->toArray();
            $this->assign("good_type",$good_type);
            $provinces = Db::name("area")->where("level",0)->order("id asc")->field("id,name")->select()->toArray();
            $this->assign("provinces",$provinces);
            
            return $this->fetch();
        }
        
    }

     /**
    * @NodeAnotation(title="编辑")
    */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $flag = $this->model->where('id',$post['id'])->find();
            if(empty($post['goodsArr'])){
                $this->error('商品不能为空');
            } 
            if(empty($post['contact_phone'])){
                $this->error('联系电话不能为空');
            }
            //dump(!preg_match("/^1[34578]\d{9}$/", $post['contact_phone']));die;
            // if (!preg_match("/^1[34578]\d{9}$/", $post['contact_phone'])) {
            //     $this->error('联系电话格式不正确');
            // } 
            if(empty($post['provinces'])){
                $this->error('省不能为空');
            }
        
            if(empty($post['consignee'])){
                $this->error('收货人不能为空');
            }
            if(empty($post['address'])){
                $this->error('收货地址不能为空');
            }
            if(empty($post['amount_collected'])){
                $this->error('收款金额不能为空');
            }
            if(empty($post['collection_voucher'])){
                $this->error('收款凭证不能为空');
            }
            $goodsArr = $post['goodsArr'];
            foreach($goodsArr as $k=>$v){
                $goods = Db::name("goods")->where("id",$v["gid"])->find();
                $v["good_bottom_price"] = $goods["bottom_price"];
                $goodsArr[$k] = $v;
            }
            $lisy = [];
            foreach($goodsArr as $ke=>$va){
                $flsst = bcmul($va["good_bottom_price"],$va["num"]);
                array_push($lisy,$flsst);
            }
            $order_bottom_price = array_sum($lisy);
       
            //status 1保存   2确定下单->待审核
            if(empty($post['status'])){
                $this->error('状态不能为空');
            }
            $data = [
                "order_bottom_price"=>$order_bottom_price,
                'remark'=>$post['remark'],//备注
                'consignee'=>$post['consignee'],//收货人
                'contact_phone'=>$post['contact_phone'],//联系电话
                'amount_collected'=>$post['amount_collected'],//收款金额
                'collection_voucher'=>$post['collection_voucher'],//收款凭证
                'is_cooperate'=>$post['is_cooperate'],//是否合作快递
                'cooperative_express'=>$post['cooperative_express'],//指定快递名称
                'provinces'=>$post['provinces'],//省
                'city'=>$post['city'],//市
                'area'=>$post['area'],//区
                'address'=>$post['address'],//详细地址
                "status"=>$post['status']
            ];
                //添加未读消息提示
            if($post['status'] == 2){
                Db::name("message_prompt")->insert([
                    "oid"=>$post['id'],
                    "type"=>1
                ]);
            }
       
            try {
               $this->model->where('id',$post['id'])->update($data);
               Db::name('order_item')->where("oid",$post['id'])->delete();
               //编辑商品信息 
                foreach($goodsArr as $k=>$v){
                    $v["oid"] = $post['id'];
                    $goodsArr[$k] = $v;
                }
                Db::name('order_item')->insertAll($goodsArr); 
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功');
        }else{
            $post = $this->request->param(); 
            $row = $this->model->where('id',$post['id'])->find();
            $good_type = Db::name("good_type")->order("id desc")->select()->toArray();
            $order_item = Db::name("order_item")->where("oid",$post['id'])->select()->toArray();
            $provinces = Db::name("area")->where("level",0)->order("id asc")->field("id,name")->select()->toArray();
            $this->assign("provinces",$provinces);

            $this->assign("good_type",$good_type);
            $this->assign('order_item', $order_item);
            $this->assign('row', $row);
        }
        return $this->fetch();
    }

    //生成条形码
    public function txm($oid){
        $bar_code_num = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $oid;
         /* getBarcode($code, $type, $widthFactor = 2, $totalHeight = 30, $color = 'black')
        code：条形码数据

        type：条形码的类型，使用在类中定义的常量，具体参数可参考github

        widthFactor：条形码的宽度

        totalHeight：条形码高度

        color：条形码的颜色*/

        //生成png、jpg类型的图片条形码
        //$generatorJPG = new \Picqer\Barcode\BarcodeGeneratorJPG(); 
        $generator = new \Picqer\Barcode\BarcodeGeneratorPNG();

        $barcode = $generator->getBarcode($bar_code_num, $generator::TYPE_CODE_128);
        $filename = time().rand(0, 1000).".png";
        //条形码图片保存路由
        file_put_contents("crmimg/".$filename,$barcode);
        $upload_path = "crmimg/";
        $domain = ($this->isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']; //获取域名
        
        //生成图片路由
        $save_path =$domain.'/' . $upload_path .$filename;

        Db::name("order")->where("id",$oid)->update(["bar_code_img"=>$save_path,"bar_code_num"=>$bar_code_num]);

    }

    public function city(){
        if($this->request->isAjax()){
            $post = $this->request->param();
            if(empty($post['pid'])){
                $this->error('省id不能为空');
            }
            $city = Db::name("area")->where("pid",$post['pid'])->order("id asc")->field("id,name")->select()->toArray();
            $res = [
                "code"=>1,
                "msg"=>"获取成功",
                "data"=>$city
            ];
            return $res;
        }
        
    }

    public function area(){
        if($this->request->isAjax()){
            $post = $this->request->param();
            if(empty($post['cid'])){
                $this->error('市id不能为空');
            }
            $quarr = Db::name("area")->where("pid",$post['cid'])->order("id asc")->field("id,name")->select()->toArray();
            $res = [
                "code"=>1,
                "msg"=>"获取成功",
                "data"=>$quarr
            ];
            return $res;
        }
      
    }

    //商品分类
    public function good_type(){
        $list = Db::name("good_type")->order("id asc")->field("id,title")->select()->toArray();
        $res = [
            "code"=>1,
            "msg"=>"获取成功",
            "data"=>$list
        ];
        return $res;
    }

    //商品列表
    public function get_goodsarr(){
        // $where = [
        //     ['id','=', 253],
        //     ['is_delete','>=', 1], 
        //     ['phone','like', '%186%'], 
        //     ['sex','<>', '女'],
        //     ['create_time','between',['2020-05-12','2022-01-11']], 
        //    ];
        // $result = Db::name('user_card')->where($where)->whereNotNull('birthday')->select(); 
        if($this->request->isAjax()){
            $param = $this->request->param();
     
            $where = [];
            if(!empty($param['title']) && isset($param['title']) || !empty($param['good_type_id']) && isset($param['good_type_id']))
            {
                $where[] = [
                    ['title', 'like', "%{$param['title']}%"],
                    ['good_type_id', '=', $param['good_type_id']]
                ];
            }
            $goods = Db::name("goods")->where("status",0)->where($where)->order("id desc")->select()->toArray();
            foreach ($goods as $k => $v){
                //分类
                $good_type = Db::name('good_type')->where('id',$v['good_type_id'])->field('title')->find();
                $v['good_type_name'] = $good_type['title'];
    
                $goods[$k] = $v;
            }
        }else{
            $goods = Db::name("goods")->where("status",0)->order("id desc")->select()->toArray();
            foreach ($goods as $k => $v){
                //分类
                $good_type = Db::name('good_type')->where('id',$v['good_type_id'])->field('title')->find();
                $v['good_type_name'] = $good_type['title'];
    
                $goods[$k] = $v;
            }
          
        }
        
        $res = [
            "code"=>1,
            "msg"=>"获取成功",
            "data"=>$goods
        ];
        return $res;
       
    }

    //订单详情   return json($data);
    public function ord_detail(){
       
       if ($this->request->isAjax()) {
            $param = $this->request->param();
            $session = session("admin");
           
            
            $row = Db::name("order")->where("id",$param["id"])->find();
            $admin = Db::name("system_admin")->where("id",$row["kahuna_id"])->find();

            $order_item = Db::name("order_item")->where("oid",$param["id"])->select()->toArray();
            
           
            $row["create_time"] = date("Y-m-d H:i:s",$row["create_time"]);
            $row["order_item"] = $order_item;
            if(!empty($row["void_picture"])){
                $row["void_picture"] = explode(",",$row["void_picture"]);
            }
            //收款凭证
            if(!empty($row["collection_voucher"])){
                $row["collection_voucher"] = explode(",",$row["collection_voucher"]);
            }
            if(!empty($admin["employee_name"])){
                $row["new_employee_name"] = $admin["employee_name"];
            }else{
                $row["new_employee_name"] ="";
            }

            $receipt_issue_detailed = Db::name("receipt_issue_detailed")->where("tracking_numbercr",$row["courier_number"])->find();
            if(!empty($receipt_issue_detailed["discrepancy"])){
                $row["discrepancy"] = $receipt_issue_detailed["discrepancy"];
            }else{
                $row["discrepancy"] ="";
            }

            $row["completed_time"] = date("Y-m-d H:i:s",$row["completed_time"]);
           
            $this->success('获取成功', $row);
        }
    }

    //获取省
    public function get_preaive(){
        $list = Db::name("area")->where("level",0)->field("id,name")->select()->toArray();
        return json([
            "code"=>1,
            "data"=>$list
        ]);
    }

    //取消订单
    public function cancel_order(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ret = $this->model->where('id', $post['id'])->where('status', 2)->find();
            if (empty($ret)) {
                $this->error('当前订单状态不能取消');
            }
            $this->model->where('id', $post['id'])->update(["status"=>7]);
            $this->success('取消成功', '');
        }
    }

    //变更订单申请
    public function change_information(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ret = $this->model->where('id', $post['id'])->where('status', "in","3,5,6,10")->find();
            if (empty($ret)) {
                $this->error('当前订单状态不能变更');
            }
            //1收货信息，2订单商品
            if(empty($post['change_info'])){
                $this->error('变更信息不能为空');
            }
            $this->model->where('id', $post['id'])->update(["is_change"=>2,"change_info"=>$post["change_info"],"change_status"=>1,"change_application_time"=>time(),"change_reason"=>""]);
            //添加未读消息提示
            Db::name("message_prompt")->insert([
                "oid"=>$post['id'],
                "type"=>2
            ]);
            $this->success('申请成功', '');
        }
    }

    //订单驳回
    public function order_refuse(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ret = $this->model->where('id', $post['id'])->where('status',2)->find();
            if (empty($ret)) {
                $this->error('当前订单状态不能驳回');
            }
            if(empty($post['reason'])){
                $this->error('驳回原因不能为空');
            }
            $this->model->where('id', $post['id'])->update([
                "reason"=>$post["reason"],
                "status"=>4,
            ]);
            $this->success('驳回成功', '');
        }
    }

    //订单通过
    public function pass_through(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ret = $this->model->where('id', $post['id'])->where('status',2)->find();
            if (empty($ret)) {
                $this->error('当前订单状态不能通过');
            }
            $this->model->where('id', $post['id'])->update([
                "status"=>3,
            ]);
            $this->success('操作成功', '');
        }
    }

    //批量预约合作快递
    public function batch_reservation(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if (empty($post["id"])) {
                $this->error('订单id不能为空');
            }
            $oid = explode(",",$post["id"]);
            foreach($oid as $k=>$v){
                $ord = $this->model->where('id', $v)->find();
               
                if (!empty($ord["courier_number"])) {
                    $this->error("当前有已预约递订单,无法预约");
                }
                $ret = $this->model->where('id', $v)->where('is_cooperate',2)->find();
                if (!empty($ret)) {
                    $this->error('当前有非合作快递订单,无法预约');
                }
                $qwe = $this->model->where('id', $v)->where('status',3)->where('is_cooperate',1)->find();
                if (empty($qwe)) {
                    $this->error('预约失败',$ord["order_no"]);
                }
                $this->model->where('id', $v)->update(["status"=>5]);
                //电子面单下单
                // $flag = $this->PlaceOrder($v);
                // if($flag["code"] == 1){
                //     $this->model->where('id', $v)->update(["status"=>5]);
                // }else{
                //     $this->error($flag["data"]);
                // }
            }
            $this->success('预约成功');
        }
    }

    //批量打印快递
    public function batch_print(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if (empty($post["id"])) {
                $this->error('订单id不能为空');
            }
            $oid = explode(",",$post["id"]);
            foreach($oid as $k=>$v){
                $ord = $this->model->where('id', $v)->find();
                if (!empty($ord["courier_number"])) {
                    $this->error("当前有已打印订单,无法打印");
                }
                if ($ord["status"] != 5) {
                    $this->error("当前订单未预约,无法打印");
                }
                $ret = $this->model->where('id', $v)->where('is_cooperate',2)->find();
                if (!empty($ret)) {
                    $this->error('当前有非合作快递订单,无法预约');
                }
                //电子面单下单
                $flag = $this->PlaceOrder($v);
                if($flag["code"] == 1){
                    //$this->success('预约成功');
                    //$this->model->where('id', $v)->update(["status"=>5]);
                }else{
                    $this->error($flag["data"]);
                }
            }
            $this->success('打印成功');
        }
    }


    //立即预约快递->改为打印
    public function subscribe_kd(){
         if ($this->request->isAjax()) {
            $post = $this->request->param();
            if (empty($post["id"])) {
                $this->error('订单id不能为空');
            }
            $ret = $this->model->where('id', $post['id'])->where('status',5)->where('is_cooperate',1)->find();
            if (empty($ret)) {
                $this->error('当前订单不能预约');
            }
            //电子面单下单
           $flag = $this->PlaceOrder($post["id"]);
           if($flag["code"] == 1){
                $this->success('下单成功',$flag["data"]);
           }else{
                $this->error('下单失败',$flag["data"]);
           }
        }
    }

    //完成预约快递
    public function complete_appointment(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if (empty($post["id"])) {
                $this->error('订单id不能为空');
            }
            //is_cooperate 1合作快递 ，2其它快递
            if (empty($post["is_cooperate"])) {
                $this->error('快递类型不能为空');
            }
            $ret = $this->model->where('id', $post['id'])->where('status',3)->find();
            if (empty($ret)) {
                $this->error('当前订单状态不能预约');
            }
            
            if($post["is_cooperate"] == 1 && $ret["is_cooperate"] == 1){
                // if(empty($ret["courier_number"])){
                //     $this->error('请先预约快递');
                // }
                //完成预约快递
                $this->model->where('id', $post['id'])->update(["status"=>5]);
            }elseif($post["is_cooperate"] == 2 && $ret["is_cooperate"] == 2){
                if (empty($post["cooperative_express"])) {
                    $this->error('快递名称不能为空');
                }
                if (empty($post["courier_number"])) {
                    $this->error('快递单号不能为空');
                }
                //完成预约快递
                $this->model->where('id', $post['id'])->update(["status"=>5,"cooperative_express"=>$post["cooperative_express"],"courier_number"=>$post["courier_number"]]);
            }else{
                $this->error('类型不存在');
            }
            $this->success('预约成功');
        }
    }

    // //调用快递100的电子面单下单接口  
    // public function PlaceOrder($oid){
    //         //订单数据
    //         $order = $this->model->where('id', $oid)->find()->toArray();
    //         $provinces = Db::name("area")->where("id",$order["provinces"])->value("name");
    //         $city = Db::name("area")->where("id",$order["city"])->value("name");
    //         $area = Db::name("area")->where("id",$order["area"])->value("name");
    //         $printAddr = $provinces.$city.$area.$order["address"];

    //         $order_item = Db::name("order_item")->where("oid",$oid)->field("good_name as name,num")->select()->toArray();
    //         $list = [];
    //         for($i=0;$i<count($order_item);$i++){
    //             $qwe = implode(",",$order_item[$i]);
    //             array_push($list,$qwe);
    //         }
    //         $list = implode(" ; ",$list);
        
    //         $param = array (
    //             'printType' => 'CLOUD',            // 打印类型，NON:只下单不打印（默认）；IMAGE:生成图片短链；HTML:生成html短链；CLOUD:使用快递100云打印机打印
    //             'partnerId' => 'KDGJ22346679796',  // 电子面单客户账户或月结账号  KDGJ22346679796 
    //             'partnerKey' => '7G42IHRJ',                // 电子面单密码 7G42IHRJ
    //             'net' => '290112',                       // 收件网点名称,由快递公司当地网点分配  西安南郊分部 
    //             'code' => 'ztoOpen',                      // 电子面单承载编号  code固定传ztoOpen
    //             'kuaidicom' => 'zhongtong',        // 快递公司的编码：https://api.kuaidi100.com/document/5f0ff6e82977d50a94e10237.html
    //             "customParam"=>[
    //                 "order_no"=>$order["order_no"],
    //                 "remarkre"=>$order["remark"]
    //             ],
    //             'recMan' => array (
    //                 'name' => $order["consignee"],                  // 收件人姓名
    //                 'mobile' =>$order["contact_phone"],                // 收件人的手机号，手机号和电话号二者其一必填
    //                 'tel' => $order["contact_phone"],                   // 收件人的电话号，手机号和电话号二者其一必填
    //                 'printAddr' => $printAddr,//'陕西省西安市未央区张家堡街道未央路与北二环十字东南处(大明宫向北100米路东)万象未央401',             // 收件人地址
    //                 //'company' => ''                // 收件人公司名
    //             ),
    //             'sendMan' => array (
    //                 'name' => '张三',                          // 寄件人姓名
    //                 'mobile' => '18791954363',                // 寄件人的手机号，手机号和电话号二者其一必填
    //                 'tel' => '18791954363',                   // 寄件人的电话号，手机号和电话号二者其一必填
    //                 'printAddr' => '西安市未央龙首印象城',      // 寄件人地址
    //                // 'company' => '医美公司'                    // 寄件人公司名
    //             ),
    //             'cargo' => '文件',                 // 物品名称
    //             'count' => '1',                    // 物品总数量
    //             'weight' => '0.5',                 // 物品总重量KG
    //             'payType' => 'SHIPPER',            // 支付方式
    //             'expType' => '标准快递',           // 快递类型: 标准快递（默认）、顺丰特惠、EMS经济
    //             'remark' => $list,                // 备注
    //             'siid' => 'KX100LA884BC4DEB4',                      // 打印设备编码
    //             'direction' => '0',                // 打印方向，0：正方向（默认）； 1：反方向；只有printType为CLOUD时该参数生效
    //             'tempId' => 'bc5c5fa9ed3a41209d128662e694e6e0',// 主单模板：快递公司模板V2链接：https://api.kuaidi100.com/manager/v2/shipping-label/template-shipping-label
    //             'needChild' => '0',                // 是否需要子单
    //             'needBack' => '0',                 // 是否需要回单
    //             'orderId' => $order["order_no"],                 // 贵司内部自定义的订单编号,需要保证唯一性
    //             'needSubscribe' => false,          // 是否开启订阅功能 false：不开启(默认)；true：开启
    //             'resultv2' => '0',                 // 添加此字段表示开通行政区域解析或地图轨迹功能
    //             'needDesensitization' => false,    // 是否脱敏 false：关闭（默认）；true：开启
    //             'needLogo' => true,               // 面单是否需要logo false：关闭（默认）；true：开启
    //             'height' => 150,                  // 打印纸的高度，以mm为单位
    //             'width' => 70                    // 打印纸的宽度，以mm为单位
    //         );
    //         $url = 'https://api.kuaidi100.com/label/order?method=order';// 电子面单下单接口请求地址
    //         $key = 'MSQAuGgR6655'; // 客户授权key
    //         $secret = "441dbc258c8d4c46abed2e1720b85091";//客户授权secret
            
    //         //生成13位时间戳
    //         list($msec, $sec) = explode(' ', microtime());
    //         $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

    //         //请求参数
    //         $post_data = array();
    //         $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
    //         $post_data['key'] = $key;
    //         $post_data['t'] = $t;
    //         $sign = md5($post_data['param'].$t.$key.$secret);//32位大写签名，用于验证身份，按MD5 (param +t+key+ secret)的顺序进行MD5加密，不需要加上“+”号。secret在企业管理后台获取
    //         $post_data['sign'] = strtoupper($sign);
    //         $datfg = $this->http_curl($url, $post_data);
    //         if( $datfg['success'] == true && $datfg["code"] == "200")
    //         {
    //             $this->model->where('id', $oid)->update([
    //                 "courier_number"=>$datfg['data']["kuaidinum"],//快递单号
    //                 "taskId"=>$datfg['data']["taskId"],//任务ID
    //                 "status"=>10,
    //             ]);
    //             return [
    //                 "code"=>1,
    //                 "data"=>$datfg['data']["kuaidinum"]
    //             ];
               
    //         }else{
    //             return [
    //                 "code"=>-1,
    //                 "data"=>$datfg['message']
    //             ];
    //         }
    // }    


     //调用快递100的电子面单下单接口  
     public function PlaceOrder($oid){
        //订单数据
        $order = $this->model->where('id', $oid)->find()->toArray();
        $provinces = Db::name("area")->where("id",$order["provinces"])->value("name");
        $city = Db::name("area")->where("id",$order["city"])->value("name");
        $area = Db::name("area")->where("id",$order["area"])->value("name");
        //甘肃省嘉峪关市雄关区 建新街29号楼2单元
        $printAddr = $provinces.$city.$area.$order["address"];
       // $printAddr = "甘肃省嘉峪关市区建新街29号楼2单元";
        //dump($printAddr);die;
        $order_item = Db::name("order_item")->where("oid",$oid)->field("good_name as name,num")->select()->toArray();
        $list = [];
        for($i=0;$i<count($order_item);$i++){
            $qwe = implode(",",$order_item[$i]);
            array_push($list,$qwe);
        }
        $list = implode(" ; ",$list);
    
        $param = array (
            'printType' => 'CLOUD',            // 打印类型，NON:只下单不打印（默认）；IMAGE:生成图片短链；HTML:生成html短链；CLOUD:使用快递100云打印机打印
            'partnerId' => 'KDGJ22346679796',  // 电子面单客户账户或月结账号  KDGJ22346679796 
            'partnerKey' => '7G42IHRJ',                // 电子面单密码 7G42IHRJ
            'net' => '290112',                       // 收件网点名称,由快递公司当地网点分配  西安南郊分部 
            'code' => 'ztoOpen',                      // 电子面单承载编号  code固定传ztoOpen
            'kuaidicom' => 'zhongtong',        // 快递公司的编码：https://api.kuaidi100.com/document/5f0ff6e82977d50a94e10237.html
            "customParam"=>[
                "order_no"=>$order["order_no"],
                "remarkre"=>$order["remark"]
            ],
            'recMan' => array (
                'name' => $order["consignee"],                  // 收件人姓名
                'mobile' =>$order["contact_phone"],                // 收件人的手机号，手机号和电话号二者其一必填
                'tel' => $order["contact_phone"],                   // 收件人的电话号，手机号和电话号二者其一必填
                'printAddr' => $printAddr,//'陕西省西安市未央区张家堡街道未央路与北二环十字东南处(大明宫向北100米路东)万象未央401',             // 收件人地址
                //'company' => ''                // 收件人公司名
            ),
            'sendMan' => array (
                'name' => '医美护肤',                          // 寄件人姓名
                'mobile' => '16656617666',                // 寄件人的手机号，手机号和电话号二者其一必填
                'tel' => '18791954363',                   // 寄件人的电话号，手机号和电话号二者其一必填
                'printAddr' => '陕西省西安市长安区中通快递代收点',      // 寄件人地址
               // 'company' => '医美公司'                    // 寄件人公司名
            ),
            'cargo' => '文件',                 // 物品名称
            'count' => '1',                    // 物品总数量
            'weight' => '0.5',                 // 物品总重量KG
            'payType' => 'SHIPPER',            // 支付方式
            'expType' => '标准快递',           // 快递类型: 标准快递（默认）、顺丰特惠、EMS经济
            'remark' => $list,                // 备注
            'siid' => 'KX100LA884BC4DEB4',                      // 打印设备编码
            'direction' => '0',                // 打印方向，0：正方向（默认）； 1：反方向；只有printType为CLOUD时该参数生效
            'tempId' => 'fae17bd7b28e4a10a17afad3e4b4ffed',//'bc5c5fa9ed3a41209d128662e694e6e0',// 主单模板：快递公司模板V2链接：https://api.kuaidi100.com/manager/v2/shipping-label/template-shipping-label
            'needChild' => '0',                // 是否需要子单 fae17bd7b28e4a10a17afad3e4b4ffed
            'needBack' => '0',                 // 是否需要回单
            'orderId' => $order["order_no"],                 // 贵司内部自定义的订单编号,需要保证唯一性
            'needSubscribe' => false,          // 是否开启订阅功能 false：不开启(默认)；true：开启
            'resultv2' => '0',                 // 添加此字段表示开通行政区域解析或地图轨迹功能
            'needDesensitization' => false,    // 是否脱敏 false：关闭（默认）；true：开启
            'needLogo' => true,               // 面单是否需要logo false：关闭（默认）；true：开启
            'height' => 150,                  // 打印纸的高度，以mm为单位
            'width' => 70                    // 打印纸的宽度，以mm为单位
        );
        $url = 'https://api.kuaidi100.com/label/order?method=order';// 电子面单下单接口请求地址
        $key = 'MSQAuGgR6655'; // 客户授权key
        $secret = "441dbc258c8d4c46abed2e1720b85091";//客户授权secret
        
        //生成13位时间戳
        list($msec, $sec) = explode(' ', microtime());
        $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

        //请求参数
        $post_data = array();
        $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $post_data['key'] = $key;
        $post_data['t'] = $t;
        $sign = md5($post_data['param'].$t.$key.$secret);//32位大写签名，用于验证身份，按MD5 (param +t+key+ secret)的顺序进行MD5加密，不需要加上“+”号。secret在企业管理后台获取
        $post_data['sign'] = strtoupper($sign);
        $datfg = $this->http_curl($url, $post_data);
        if( $datfg['success'] == true && $datfg["code"] == "200")
        {
            $this->model->where('id', $oid)->update([
                "courier_number"=>$datfg['data']["kuaidinum"],//快递单号
                "taskId"=>$datfg['data']["taskId"],//任务ID
                "status"=>10,
            ]);
            return [
                "code"=>1,
                "data"=>$datfg['data']["kuaidinum"]
            ];
           
        }else{
            return [
                "code"=>-1,
                "data"=>$datfg['message']
            ];
        }
}

      //自定义发货清单打印
      public function custom_print_shipping_list(){
        $post = $this->request->param();
        if(empty($post["oid"])){
            $this->error("订单id不能为空");
        }
        $order = Db::name("order")->where("id",$post["oid"])->where('status',5)->find();
        if (empty($order)) {
            $this->error('当前订单状态不能打印');
        }
        $provinces = Db::name("area")->where("id",$order["provinces"])->find();
        $city = Db::name("area")->where("id",$order["city"])->find();
        $area = Db::name("area")->where("id",$order["area"])->find();
        $order["pca"] = $provinces["name"].$city["name"].$area["name"];
       

        $order_item = Db::name("order_item")->where("oid",$post["oid"])->field("good_name as name,num,good_bottom_price as price")
                    ->paginate();
        $order_item = $order_item->toArray();
     
        $param = array (
            "tempid"=> "de215de050f449ee93a0bfb92dda4cf3",     // 模板编码，通过管理后台获取：https://api.kuaidi100.com/manager/v2/shipping-label/template-order-form
            "siid"=> "KX100LA884BC4DEB4",       // 打印设备编码，通过打印机输出的设备码进行获取
            "printType"=> "CLOUD",
            "customParam"=>[
                "good"=>$order_item["data"],
                "address"=>$order["pca"].$order["address"],
                "consignee"=>$order["consignee"],
                "contact_phone"=>$order["contact_phone"],
                "order_no"=>$order["order_no"],
                "bar_code_num"=>$order["bar_code_num"],
            ],
        ); 
        $url = 'https://api.kuaidi100.com/label/order?method=custom';// 自定义打印接口请求地址
        $key = 'MSQAuGgR6655'; // 客户授权key
        $secret = "441dbc258c8d4c46abed2e1720b85091";//客户授权secret
        
        //生成13位时间戳
        list($msec, $sec) = explode(' ', microtime());
        $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

        //请求参数
        $post_data = array();
        $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $post_data['key'] = $key;
        $post_data['t'] = $t;
        $sign = md5($post_data['param'].$t.$key.$secret);//32位大写签名，用于验证身份，按MD5 (param +t+key+ secret)的顺序进行MD5加密，不需要加上“+”号。secret在企业管理后台获取
        $post_data['sign'] = strtoupper($sign);
        $datfg = $this->http_curl($url, $post_data);
        if( $datfg['success'] == true && $datfg["code"] == "200")
        {
            $this->success("打印成功",$datfg['data']);
           
        }else{
            $this->error("打印失败",$datfg['message']);
        }
    }


    //电子面单复打接口
    public function fudadianzi(){
           
            // $http = is_https() ? 'https' : 'http';
            // $notify = $http . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . '/api/notify/express_order_callback';
            $param = array (
                'taskId' => 'IMAGE', //任务ID
                'siid' => '',  //快递100打印机,不填默认为下单时填入的siid
                    
            );
            $url = 'https://api.kuaidi100.com/label/order?method=printOld';// 电子面单复打接口请求地址
            $key = 'MSQAuGgR6655'; // 客户授权key
            $secret = "441dbc258c8d4c46abed2e1720b85091";//客户授权secret
            
            //生成13位时间戳
            list($msec, $sec) = explode(' ', microtime());
            $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    
            //请求参数
            $post_data = array();
            $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
            $post_data['key'] = $key;
            $post_data['t'] = $t;
            $sign = md5($post_data['param'].$t.$key.$secret);//32位大写签名，用于验证身份，按MD5 (param +t+key+ secret)的顺序进行MD5加密，不需要加上“+”号。secret在企业管理后台获取
            $post_data['sign'] = strtoupper($sign);
           // dump($post_data);die;
            $datfg = $this->http_curl($url, $post_data);
            dump($datfg);die;
            if( $datfg['success'] == true && $datfg["code"] == "200")
            {
                $this->success("打印成功",$datfg['data']);
               
            }else{
                $this->error("打印失败",$datfg['message']);
            }
    }

  

    /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
    protected function http_curl($url, $post_data = array())
   {
       //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $result = curl_exec($ch);
     
        $data = json_decode($result, true);
       // dump($data);die;
        return $data;
   }


   
    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        $post = $this->request->param();
        if(empty($post["checklist_id"])){
            $this->error("盘点id不能为空");
        }
        //查询数据
        $checklist = Db::name("checklist")->where("id",$post["checklist_id"])->find();
        $create_time = date("Y-m-d H:i",$checklist["create_time"]);
        if (empty($checklist)) {
            $this->error('盘点单不存在');
        }
        $list = Db::name("checklist_item")->where("checklist_id",$post["checklist_id"])->field("gid,good_type_name,stock,physical_inventory,remarks")->select()->toArray();
        foreach ($list as $k => $v){
            //商品
            $goods = Db::name('goods')->where('id',$v['gid'])->field('title')->find();
            $v['good_name'] = $goods['title'];
            $list[$k] = $v;
        }
       
        //导出数据
        $data_h = [
            ['商品名称', 'good_name'],
            ['商品分类', 'good_type_name'],
            ['库存', 'stock'],
            ['实际库存', 'physical_inventory'],
            ['备注', 'remarks'],
        ];
        $arr = [];
        foreach ($list as $k => $v) {
            $arr[$k]['good_name'] = $v['good_name'];
            $arr[$k]['good_type_name'] = $v['good_type_name'];
            $arr[$k]['stock'] = "\t".$v['stock']."\t";
            $arr[$k]['physical_inventory'] = "\t".$v['physical_inventory']."\t";
            $arr[$k]['remarks'] = $v['remarks'];

        }
        $pdata = [
            "check_no"=>$checklist['check_no'],
            "check_name"=>$checklist['check_name'],
            "outbound_name"=>$create_time,
        ];
        $fileName = date('Y-m-d H:i:s',time()) . "盘点单表.xlsx";
        $expFileName =  $fileName;
        //设置保存路径
        $basePath = 'static';
        $baseUrl  = DIRECTORY_SEPARATOR .implode(DIRECTORY_SEPARATOR, ['excel',date('Y-m-d',time())]). DIRECTORY_SEPARATOR;
        $path = $basePath.$baseUrl;
        //路径不存在则创建路径
        if(!is_dir($path)){
            mkdir($path, 0777, true);
        }
        $path = $path.$expFileName;
        $res =  Excel::exportData($arr, $data_h, $fileName,$pdata, 'xlsx',$path);
        return json([
            "code"=>1,
            "data"=>$res["data"]
        ]);
    }

    //未读消息提示
    public function unread_order_newrce(){
        if ($this->request->isAjax()) {
            //type 1新订单  2变更单  3作废单
            $list = Db::name("message_prompt")->where("status",1)->find();
            if(!empty($list)){
                return json([
                    "code"=>1,
                    "data"=>$list
                ]);
            }else{
                return json([
                    "code"=>-1,
                    "data"=>""
                ]);
            }
          
           
        }
    }

    //已读消息关闭
    public function read_order_newrce(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            //type 1新订单  2变更单  3作废单
            Db::name("message_prompt")->where("id",$post["id"])->update(["status"=>2]);
            return json([
                "code"=>1,
                "msg"=>"操作成功"
            ]);
        }
    }

    //重置出库数量
    public function order_resetting(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post["oid"])){
                $this->error("订单id不能为空");
            }
            Db::name("good_outbound_view")->where("oid",$post["oid"])->delete();
            return json([
                "code"=>1,
                "msg"=>"操作成功"
            ]);
        }
    }


    

    
 
} 